package com.sixth.oa.util;

import java.io.IOException;

import com.alibaba.fastjson.JSON;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {
	
	
	public static String httpGet(String url) throws IOException {
		OkHttpClient client = new OkHttpClient();
		Request request = new Request.Builder()
			      .url(url)
			      .build();
			  try (Response response = client.newCall(request).execute()) {
			    return response.body().string();
			  }
	}
	
	
	
	public static String httpPost(String url,Object obj) {
	 	
	 	OkHttpClient client = new OkHttpClient();
	 	String json = JSON.toJSONString(obj);
	 	MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
	 	RequestBody body = RequestBody.create(mediaType, json);
	 	System.out.println("构造的json："+json);
       // RequestBody body=setRequestBody(bodyParams);
        //构造Request
        Request.Builder requestBuilder = new Request.Builder();
        Request request = new Request.Builder()
		        .url(url)
		        .header("Content-Type", "application/json;charset=utf-8;")
		        .build();
        request = requestBuilder.post(body).url(url).build();
        //将Request封装为Call
        Call call = client.newCall(request);
        //执行Call，得到response
        Response response = null;
        try {
            response = call.execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return response.toString();
        }
    }
	
}
